package com.yl.chainStore.services

import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.yl.chainStore.common.Constants
import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.entity.customer.*
import com.yl.chainStore.entity.sick.CustomerSubscribeLog
import com.yl.chainStore.entity.sick.SickMedicalHistory
import com.yl.chainStore.entity.sick.SickMedicalRecords
import com.yl.chainStore.entity.sick.SickMedicalRecordsDetail
import com.yl.chainStore.entity.system.CompanyDictionaryDetail
import com.yl.chainStore.mapper.customer.CustomerInfoMapper
import com.yl.chainStore.mapper.customer.CustomerInfoPhoneMapper
import com.yl.chainStore.mapper.customer.CustomerInfoSecondSourceMapper
import com.yl.chainStore.mapper.customer.CustomerInfoSourceDistMapper
import com.yl.chainStore.mapper.dbimport.CustomerInfoDbMapper
import com.yl.chainStore.mapper.dbimport.CustomerSubscribeLogDbMapper
import com.yl.chainStore.mapper.dbimport.SickMedicalHistoryDbMapper
import com.yl.chainStore.mapper.dbimport.SickMedicalRecordsDetailDbMapper
import com.yl.chainStore.mapper.sick.CustomerSubscribeLogMapper
import com.yl.chainStore.mapper.sick.SickMedicalHistoryMapper
import com.yl.chainStore.mapper.sick.SickMedicalRecordsDetailMapper
import com.yl.chainStore.mapper.sick.SickMedicalRecordsMapper
import com.yl.chainStore.mapper.system.CompanyDictionaryDetailMapper
import com.yl.chainStore.pojo.vo.sick.CustomerSubscribeLogSelectVo
import com.yl.chainStore.util.DateUtil
import com.yl.chainStore.util.setTimeTo15Min
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.entity.CompanyUser
import com.yl.users.mapper.CompanyUserMapper
import com.yl.users.services.ISysCompanyService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.text.SimpleDateFormat
import java.util.*

@Service
class DbImportServiceImpl(
	private val customerInfoDbMapper: CustomerInfoDbMapper,
	private val customerInfoMapper: CustomerInfoMapper,
	private val companyUserMapper: CompanyUserMapper,
	private val customerInfoSecondSource: CustomerInfoSecondSourceMapper,
	private val customerInfoSourceDistMapper: CustomerInfoSourceDistMapper,
	private val companyDictionaryDetailMapper: CompanyDictionaryDetailMapper,
	private val customerInfoPhoneMapper: CustomerInfoPhoneMapper,

	private val sickMedicalHistoryDbMapper: SickMedicalHistoryDbMapper,
	private val sickMedicalHistoryMapper: SickMedicalHistoryMapper,

	private val customerSubscribeLogDbMapper: CustomerSubscribeLogDbMapper,
	private val customerSubscribeLogMapper: CustomerSubscribeLogMapper,

	private val sickMedicalRecordsDetailDbMapper: SickMedicalRecordsDetailDbMapper,
	private val sickMedicalRecordsDetailMapper: SickMedicalRecordsDetailMapper,
	private val sickMedicalRecordsMapper: SickMedicalRecordsMapper,
) : IdbImportService {

	@Autowired
	private lateinit var iSysCompanyService: ISysCompanyService

	@Autowired
	private lateinit var iCustomerInfoService: ICustomerInfoService

	@Autowired
	private lateinit var iWebCompanyDeptService: IWebCompanyDeptService

	@Autowired
	private lateinit var iCompanyUserOperationLogService:ICompanyUserOperationLogService

	private val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")

	private val timeSdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

	private val daySdf = SimpleDateFormat("yyyy-MM-dd")
	override fun importCustomer(): ResponseBody {
		val selectList = customerInfoDbMapper.selectList(QueryWrapper())

		val companyUserNameId = mutableMapOf<String, Long>()
		val senSourceMap = mutableMapOf<String, CustomerInfoSecondSource>()
		val thirdSourceMap = mutableMapOf<String, Long>()
		val companyId = getContext().companyId
		val userId = getContext().userId
		val errorMsg = StringBuffer()
		val mobileType = mutableMapOf<String, Long>()
		val phoneType = mutableMapOf<String, Long>()

		val selectList2 = companyDictionaryDetailMapper.selectList(
			Wrappers.query<CompanyDictionaryDetail?>()
				.eq("dist_id", Constants.DistId.CUSTOMER_MOBILE_TO_CUSTOMER_TYPE)
				.eq("company_id", companyId)
				.orderByAsc("order_num")
		)
		for (dist in selectList2) {
			mobileType[dist.itemName] = dist.id
		}
		val selectList3 = companyDictionaryDetailMapper.selectList(
			Wrappers.query<CompanyDictionaryDetail?>()
				.eq("dist_id", Constants.DistId.CUSTOMER_PHONE_TO_CUSTOMER_TYPE)
				.eq("company_id", companyId)
				.orderByAsc("order_num")
		)

		for (dist in selectList3) {
			phoneType[dist.itemName] = dist.id
		}

		for (cdb in selectList) {
			val customerInfo = CustomerInfo(
				id = 0,
				name = cdb.realName ?: "",
				historySickNum = cdb.sickNum ?: "",
				nickname = cdb.nickName,
				certificateNum = cdb.idCard,
				qqAccount = cdb.qqAccount,
				wechatAccount = cdb.wechat,
				addressDetail = cdb.address,
				email = cdb.email,
				remark = cdb.remark
			)
			if (cdb.sex == "男") {
				customerInfo.gender = TypeEnum.USER_GENDER_BOY
			} else {
				customerInfo.gender = TypeEnum.USER_GENDER_GIRL
			}
			if (cdb.createUser == null || cdb.createUser.isNullOrEmpty()) {
				customerInfo.createUserId = userId
			} else {
				customerInfo.createUserId = getUserByMap(cdb.createUser ?: "", companyUserNameId)
			}
			if (cdb.createTimeStr != null && cdb.createTimeStr != "") {

				customerInfo.createTime = preDate(cdb.createTimeStr!!)
			}
			if (cdb.birthDate != null && cdb.birthDate != "") {
				customerInfo.birthDate = preDate(cdb.birthDate!!)
			}
			if (cdb.firstSrouce != null && cdb.firstSrouce != "") {
				if (cdb.firstSrouce == "员工介绍") {
					cdb.firstSrouce = "介绍"
				}
				customerInfo.firstSource = cdb.firstSrouce
				if (cdb.secondSrouce != null && cdb.secondSrouce != "") {
					var senId = senSourceMap[cdb.firstSrouce + "-" + cdb.secondSrouce]
					if (senId == null) {
						val secList = customerInfoSecondSource.selectList(
							Wrappers.query<CustomerInfoSecondSource?>().eq(
								"name", cdb.secondSrouce
							).eq("parent_value", cdb.firstSrouce)
						)
						senId = if (secList.isEmpty()) {
							val sec = CustomerInfoSecondSource(
								id = 0L,
								name = cdb.secondSrouce!!,
								parentValue = cdb.firstSrouce!!
							)
							customerInfoSecondSource.insert(sec)
							sec
						} else {
							secList[0]
						}
					}
					customerInfo.secondSourceId = senId!!.id
					senSourceMap[cdb.firstSrouce + "-" + cdb.secondSrouce] = senId
					if (cdb.thirdSrouce != null && cdb.thirdSrouce != "") {
						if (senId.subType == TypeEnum.CUSTOMER_INFO_SOURCE_DIST) {
							var thirdId =
								thirdSourceMap[cdb.firstSrouce + "-" + cdb.secondSrouce + "-" + cdb.thirdSrouce]
							if (thirdId == null) {
								val thirdList = customerInfoSourceDistMapper.selectList(
									Wrappers.query<CustomerInfoSourceDist?>().eq(
										"parent_id", senId.id
									).eq("source_value", cdb.thirdSrouce)
								)
								thirdId = if (thirdList.isEmpty()) {
									val third = CustomerInfoSourceDist(
										id = 0L,
										parentId = senId.id,
										sourceValue = cdb.thirdSrouce!!
									)
									customerInfoSourceDistMapper.insert(third)
									third.id
								} else {
									thirdList[0].id
								}
								customerInfo.sourceDistId = thirdId
								thirdSourceMap[cdb.firstSrouce + "-" + cdb.secondSrouce + "-" + cdb.thirdSrouce] =
									thirdId
							}
						} else if (senId.subType == TypeEnum.CUSTOMER_INFO_SOURCE_COMPANY_USER) {
							customerInfo.sourceCompanyUserId = getUserByMap(cdb.thirdSrouce ?: "", companyUserNameId)
						} else {
							//患者应该全部患者加完之后处理

						}
					}

				}
			}
			customerInfoMapper.insert(customerInfo)
			val phoneList = mutableListOf<CustomerInfoPhone>()
			if (cdb.mobile != null && cdb.mobile != "") {
				val phones = cdb.mobile!!.split("；")
				for (phone in phones) {
					val phoneStr = phone.split("：")
					if (phoneStr.size != 2) {
						continue
					}
					val mobileTypeId = getMobileType(phoneStr[0], mobileType)
					phoneList.add(
						CustomerInfoPhone(
							id = 0,
							customerId = customerInfo.id,
							phoneToCustomerType = mobileTypeId,
							phone = phoneStr[1]
						)
					)

				}
			}
			if (cdb.phone != null && cdb.phone != "") {
				val phones = cdb.phone!!.split("；")
				for (phone in phones) {
					val phoneStr = phone.split("：")
					if (phoneStr.size != 2) {
						continue
					}
					val phoneTypeId = getPhoneType(phoneStr[0], phoneType)

					phoneList.add(
						CustomerInfoPhone(
							id = 0,
							customerId = customerInfo.id,
							phoneType = TypeEnum.CUSTOMER_PHONE_TYPE_PHONE,
							phoneToCustomerType = phoneTypeId,
							phone = phoneStr[1]
						)
					)

				}
			}
			for (p in phoneList) {
				customerInfoPhoneMapper.insert(p)
			}
			val customerDeptConfig = CustomerDeptConfig(
				customerId = customerInfo.id,
			)
			if (cdb.masterDoctor != null && cdb.masterDoctor != "") {
				customerDeptConfig.firstChargeUserId = getUserByMap(cdb.masterDoctor ?: "", companyUserNameId)
			}
			if (cdb.consult != null && cdb.consult != "") {
				customerDeptConfig.secondChargeUserId = getUserByMap(cdb.consult ?: "", companyUserNameId)
			}
			iWebCompanyDeptService.setDeptConfig(customerDeptConfig)
			val record = SickMedicalRecords(
				customerId = customerInfo.id,

				)
			if (!cdb.firstSickDoctor.isNullOrEmpty()) {
				record.doctorId = getUserByMap(cdb.firstSickDoctor ?: "", companyUserNameId)
			}
			if (!cdb.firstSickTime.isNullOrEmpty()) {
				record.startTime = preDate(cdb.firstSickTime!!)
			}
			iCustomerInfoService.createMedicalRecords(record)
		}
		return returnSuccess(errorMsg)
	}

	override fun importCustomerSourceByCustomer(): ResponseBody {
		val selectList = customerInfoDbMapper.selectList(QueryWrapper())
		val senSourceMap = mutableMapOf<Long, CustomerInfoSecondSource>()
		val errorMsg = StringBuffer()
		for (cdb in selectList) {
			if (cdb.thirdSrouce != null && cdb.thirdSrouce != "") {
				val selectList1 = customerInfoMapper.selectList(
					Wrappers.query<CustomerInfo?>()
						.eq("history_sick_num", cdb.sickNum ?: "")
						.eq("name", cdb.realName)
				)
				if (selectList1.isEmpty()) {
					errorMsg.append(cdb.sickNum + ":" + cdb.realName + ":" + "未找到患者")
					continue
				}
				if (selectList1.size > 1) {
					errorMsg.append(cdb.sickNum + ":" + cdb.realName + ":" + "患者多个")
					continue
				}
				val customer = selectList1[0]
				if (customer.secondSourceId == null) {
					continue
				}
				var sen = senSourceMap[customer.secondSourceId]
				if (sen == null) {
					val secList = customerInfoSecondSource.selectList(
						Wrappers.query<CustomerInfoSecondSource?>().eq(
							"name", cdb.secondSrouce
						).eq("parent_value", cdb.firstSrouce)
					)
					//因为之前导入的时候加了，所以一定会有
					sen = secList[0]
					senSourceMap[customer.secondSourceId!!] = sen
				}
				if (sen!!.subType != TypeEnum.CUSTOMER_INFO_SOURCE_CUSTOMER_INFO) {
					continue
				}
				val customerList =
					customerInfoMapper.selectList(Wrappers.query<CustomerInfo?>().eq("name", cdb.thirdSrouce))
				if (customerList == null || customerList.size == 0) {
					errorMsg.append(cdb.sickNum + ":" + cdb.realName + "(推荐人 " + cdb.thirdSrouce + " 找不到)")
					continue
				} else if (customerList.size > 1) {
					errorMsg.append(cdb.sickNum + ":" + cdb.realName + "(推荐人 " + cdb.thirdSrouce + " 有多个)")
					continue
				}
				customer.sourceCustomerId = customerList[0].id
				customerInfoMapper.updateById(customer)
				iCustomerInfoService.addAssociatedCustomer(
					CustomerInfoAssociated(
						id = 0,
						customerId = customer.id,
						associatedCustomerId = customerList[0].id,
						associatedName = Constants.StrShow.CUSTOMER_TO_CUSTOMER_SOURCE_ASSOCIATED
					)
				)
			}
		}
		return returnSuccess(errorMsg)

	}

	override fun importCustomerHistory(): ResponseBody {
		val selectList = sickMedicalHistoryDbMapper.selectList(QueryWrapper())
		val companyUserMap = mutableMapOf<String, Long>()
		val errorMsg = StringBuffer()
		for (db in selectList) {
			val selectList1 = customerInfoMapper.selectList(
				Wrappers.query<CustomerInfo?>()
					.eq("history_sick_num", db.historyNum ?: "")
					.eq("name", db.customerName)
			)
			if (selectList1.isEmpty()) {
				errorMsg.append(db.historyNum + ":" + db.customerName + ":" + "未找到患者")
				continue
			}
			if (selectList1.size > 1) {
				errorMsg.append(db.historyNum + ":" + db.customerName + ":" + "患者多个")
				continue
			}
			val customer = selectList1[0]
			val doctorId = if (db.sickHistoryDoctor != null && db.sickHistoryDoctor != "") {
				getUserByMap(db.sickHistoryDoctor!!, companyUserMap)
			} else {
				getContext().userId
			}


			val history = SickMedicalHistory(
				id = 0L,
				customerId = customer.id,
				doctorId = doctorId,
				actionChief = db.actionInChief ?: "",
				remark = db.remark
			)

			if (db.createTime != null && db.createTime != "") {
				history.createTime = preDate(db.createTime!!)

			}
			if (db.sickHistoryDoctor != null && db.sickHistoryDoctor != "") {
				history.createUserId = getUserByMap(db.sickHistoryDoctor!!, companyUserMap)
			}

			if (db.sickHistoryDoctor != null && db.sickHistoryDoctor != "") {
				history.createUserId = getUserByMap(db.sickHistoryDoctor!!, companyUserMap)
			}
			if (db.sickTime != null && db.sickTime != "") {
				history.seeDoctorTime = preDate(db.sickTime!!)
			}
			val otherJson = JSONObject()
			otherJson["主诉"] = db.actionInChief
			otherJson["医嘱"] = db.advice
			otherJson["处置"] = getHaveToothStringToJsonArray(db.disposal ?: "")
			otherJson["备注"] = db.remark
			otherJson["诊断"] = getHaveToothStringToJsonArray(db.diagnosis ?: "")
			otherJson["既往史"] = db.previousHistory
			otherJson["现病史"] = db.hpi
			otherJson["口腔检查"] = getHaveToothStringToJsonArray(db.oral ?: "")
			otherJson["治疗计划"] = getHaveToothStringToJsonArray(db.plan ?: "")
			otherJson["辅助检查"] = getHaveToothStringToJsonArray(db.auxiliaryExamination ?: "")
			history.other = otherJson
			sickMedicalHistoryMapper.insert(history)
		}
		return returnSuccess()
	}

	override fun importSubLog(): ResponseBody {
		val selectList = customerSubscribeLogDbMapper.selectList(QueryWrapper())
		val errorMsg = StringBuffer()
		val companyUserMap = mutableMapOf<String, Long>()
		for (db in selectList) {
			val selectList1 = customerInfoMapper.selectList(
				Wrappers.query<CustomerInfo?>()
					.eq("history_sick_num", db.sickNum ?: "")
					.eq("name", db.name)
			)
			if (selectList1.isEmpty()) {
				errorMsg.append(db.sickNum + ":" + db.name + ":" + "未找到患者")
				continue
			}
			if (selectList1.size > 1) {
				errorMsg.append(db.sickNum + ":" + db.name + ":" + "患者多个")
				continue
			}
			val customer = selectList1[0]
			if (db.content == null) {
				continue
			}
			val contents = db.content!!.split("； 预约时间：")
			val index = 1
			for (c in contents) {
				println(c)
				if (c == "") {
					continue
				}
				val values = c.split(" | ")
				if (values.size != 3) {
					errorMsg.append(db.sickNum + ":" + db.name + ":" + index.toString() + ":" + "内容不对")
					continue
				}
				val timeStr = values[0].replace("预约时间：", "")
				val doctorName = values[1].replace("预约医生：", "")
				val remark = values[2].replace("备注：", "")
				val times = timeStr.split("--")
				if (times.size != 2) {
					errorMsg.append(db.sickNum + ":" + db.name + ":" + index.toString() + ":" + "时间错误")
					continue
				}
				val startTime = preTime(times[0])
				val endTime = preTime(times[1])
				setTimeTo15Min(startTime)
				setTimeTo15Min(endTime)
				val log = CustomerSubscribeLog(
					id = 0L,
					customerId = customer.id,
					subscribeTime = startTime,
					timeLength = getTimeToTimeMin(startTime, endTime),
					remark = remark,
					createTime = startTime
				)
				if (index != 1) {
					log.clinicType = TypeEnum.SICK_MEDICAL_RECORD_DETAIL_TYPE_AGAIN
				}
				log.doctorId = getUserByMap(doctorName, companyUserMap)


				customerSubscribeLogMapper.insert(log)
			}
		}
		return returnSuccess(errorMsg)
	}

	override fun importCustomerRecordDetail(): ResponseBody {
		val list = sickMedicalRecordsDetailDbMapper.selectList(QueryWrapper())
		val errorMsg = StringBuffer()
		val companyUserMap = mutableMapOf<String, Long>()
		for (db in list) {
			val selectList1 = customerInfoMapper.selectList(
				Wrappers.query<CustomerInfo?>()
					.eq("history_sick_num", db.sickNum ?: "")
					.eq("name", db.customerName)
			)
			if (selectList1.isEmpty()) {
				errorMsg.append(db.sickNum + ":" + db.customerName + ":" + "未找到患者")
				continue
			}
			val cus = selectList1[0]
			val onGoingRecord = sickMedicalRecordsMapper.selectList(
				Wrappers.query<SickMedicalRecords?>()
					.eq("status", Status.ONGOING)
					.eq("customer_id", cus.id)
					.orderByDesc("start_time")
			)
			val vo = SickMedicalRecordsDetail(
				id = 0L,
				recordId = 0L
			)
			if (onGoingRecord.isNotEmpty()) {
				vo.recordId = onGoingRecord[0].id
			} else {
				//没有就诊记录，创建一个就诊记录，
				val record = SickMedicalRecords(
					customerId = cus.id,
					doctorId = vo.masterUserId,
					status = Status.ONGOING,
					actionChief = "暂无"
				)
				sickMedicalRecordsMapper.insert(record)
				vo.recordId = record.id
			}
			if(db.seeDoctorTime == null){
				errorMsg.append(db.sickNum + ":" + db.customerName + ":" + "没有就诊时间")
				continue
			}
			vo.startTime = preTime(db.seeDoctorTime!!)
			vo.toDay = preTime(db.seeDoctorTime!!)
			if(db.cureEndTime != null){
				vo.endTime = preTime(db.cureEndTime!!)
			}
			if(db.docName != null && db.docName!!.isNotEmpty()){
				vo.masterUserId = getUserByMap(db.docName!!,companyUserMap)
			}

			vo.remark = db.remark
			vo.status = Status.COMPLETE_TREATMENT

			val customerToDayLog = customerSubscribeLogMapper.getSubscribeLogList(CustomerSubscribeLogSelectVo(
				day = vo.startTime,
				customerId = vo.customerId
			))
			if (customerToDayLog.isNotEmpty()) {
				vo.subscribeLogId = customerToDayLog[0].id
			}
			sickMedicalRecordsDetailMapper.insert(vo)
			iCompanyUserOperationLogService.addLog(
				associatedId = vo.id,
				modelType = TypeEnum.COMPANY_USER_OPERATION_LOG_MODEL_TYPE_RECORD,
				tableType = TypeEnum.COMPANY_USER_OPERATION_LOG_TABLE_TYPE_RECORD_DETAIL,
				updateType = TypeEnum.COMPANY_USER_OPERATION_LOG_UPDATE_TYPE_NEW_ADD,
				beforeObj = null,
				afterObj = vo,
				customerId = cus.id,
				createUserId = getContext().userId
			)
		}
		return returnSuccess(errorMsg)
	}


	private fun getTimeToTimeMin(startTime: Date, endTime: Date): Int {
		val times = endTime.time - startTime.time
		val toInt = times.div(1000 * 60).toInt()
		val res = toInt - (toInt % 15)

		return if (res >= 15) {
			res
		} else {
			15
		}
	}

	private fun getHaveToothStringToJsonArray(s: String): JSONArray {
		val array = JSONArray()
		val firstJson = createToothContent()
		if (s == "") {
			array.add(firstJson)
			return array
		}
		val split = s.split(",牙位：")
		var index = 0
		for (content in split) {

			val json = if (index == 0) {
				firstJson
			} else {
				createToothContent()
			}
			array.add(json)

			val split1 = content.split(";内容：")
			println(content)
			if (split1.size == 1) {
				val a = 1
				val b = 2
			}
			var tooth = split1[0]
			if (index == 0) {
				tooth = tooth.replace("牙位：", "")
			}
			val sickContent = split1[1]
			for (chickS in tooth.split(",")) {
				chickTooth(chickS, json)
			}
			json["val"] = sickContent
			index++
		}


		return array
	}

	private fun createToothContent(): JSONObject {
		val jsonObject = JSONObject()
		jsonObject["val"] = ""
		jsonObject["Bleft"] = createToothArray(4)
		jsonObject["Tleft"] = createToothArray(1)
		jsonObject["isDel"] = false
		jsonObject["Bright"] = createToothArray(3)
		jsonObject["Tright"] = createToothArray(2)
		return jsonObject
	}

	private fun createToothArray(type: Int): JSONArray {
		val array = JSONArray()
		if (type == 1 || type == 4) {
			array.add(createTooth("8"))
			array.add(createTooth("7"))
			array.add(createTooth("6"))
			array.add(createTooth("5"))
			array.add(createTooth("E"))
			array.add(createTooth("4"))
			array.add(createTooth("D"))
			array.add(createTooth("3"))
			array.add(createTooth("C"))
			array.add(createTooth("2"))
			array.add(createTooth("B"))
			array.add(createTooth("1"))
			array.add(createTooth("A"))
		} else if (type == 2 || type == 3) {
			array.add(createTooth("A"))
			array.add(createTooth("1"))
			array.add(createTooth("B"))
			array.add(createTooth("2"))
			array.add(createTooth("C"))
			array.add(createTooth("3"))
			array.add(createTooth("D"))
			array.add(createTooth("4"))
			array.add(createTooth("E"))
			array.add(createTooth("5"))
			array.add(createTooth("6"))
			array.add(createTooth("7"))
			array.add(createTooth("8"))
		}
		return array
	}

	private fun createTooth(id: String): JSONObject {
		val obj = JSONObject()
		obj["id"] = id
		obj["sub"] = ""
		obj["super"] = ""
		obj["isClick"] = ""
		obj["isActive"] = false
		return obj
	}

	private fun chickTooth(s: String, json: JSONObject) {
		if (s.isEmpty()) {
			return
		}
		var f = s.substring(0, 1).toInt()
		var se = s.substring(1, 2)
		val r = f > 4
		f %= 4
		if (f == 0) {
			f = 4
		}
		val toothArray: JSONArray
		toothArray = if (f == 1) {
			json["Tleft"] as JSONArray
		} else if (f == 2) {
			json["Tright"] as JSONArray
		} else if (f == 3) {
			json["Bright"] as JSONArray
		} else {
			json["Bleft"] as JSONArray
		}
		if (r) {
			if (se == "1") {
				se = "A"
			} else if (se == "2") {
				se = "B"
			} else if (se == "3") {
				se = "C"
			} else if (se == "4") {
				se = "D"
			} else {
				se = "E"
			}
		}
		val sub = if (s.length != 2) {
			s.substring(2)
		} else {
			null
		}

		chickTooth(se, toothArray, sub)

	}

	private fun chickTooth(s: String, jsonArray: JSONArray, sub: String?) {
		for (o in jsonArray) {
			val obj = JSONObject.parseObject(o.toString())
			if (obj["id"] == s) {
				obj["isActive"] = true
				if (sub != null) {
					obj["sub"] = sub.replace("_", ",")
				}
			}
		}
	}

	private fun getUserByMap(name: String, map: MutableMap<String, Long>): Long {
		var createUserId = map[name]
		if (createUserId == null) {
			val selectList1 =
				companyUserMapper.selectList(Wrappers.query<CompanyUser?>().eq("real_name", name))
			createUserId = if (selectList1.isEmpty()) {
				val companyUser = CompanyUser(
					id = 0L,
					realName = name
				)
				iSysCompanyService.addUser(companyUser)
				companyUser.id
			} else {
				selectList1[0].id
			}
			map[name] = createUserId
		}


		return createUserId
	}

	private fun getMobileType(name: String, map: MutableMap<String, Long>): Long {
		var mobileTypeId = if (name == "本人") {
			1L
		} else {
			map[name]
		}

		if (mobileTypeId == null) {
			val companyDictionaryDetail = CompanyDictionaryDetail(
				id = 0,
				distId = Constants.DistId.CUSTOMER_MOBILE_TO_CUSTOMER_TYPE,
				itemName = name,
				orderNum = 99
			)
			companyDictionaryDetailMapper.insert(companyDictionaryDetail)
			mobileTypeId = companyDictionaryDetail.id
			map[name] = mobileTypeId

		}
		return mobileTypeId
	}

	private fun getPhoneType(name: String, map: MutableMap<String, Long>): Long {
		var mobileTypeId = map[name]

		if (mobileTypeId == null) {
			val companyDictionaryDetail = CompanyDictionaryDetail(
				id = 0,
				distId = Constants.DistId.CUSTOMER_MOBILE_TO_CUSTOMER_TYPE,
				itemName = name,
				orderNum = 99
			)
			companyDictionaryDetailMapper.insert(companyDictionaryDetail)
			mobileTypeId = companyDictionaryDetail.id
			map[name] = mobileTypeId
		}
		return mobileTypeId
	}

	private fun preDate(str: String): Date {
		return try {
			sdf.parse(str)
		} catch (e: Exception) {
			daySdf.parse(str)
		}
	}

	private fun preTime(str: String): Date {
		return try {
			timeSdf.parse(str)
		} catch (e: Exception) {
			daySdf.parse(str)
		}
	}

}

fun main() {
	val timeStr = "2018-04-16 17:59:04--2018-04-16 18:29:04"
	val times = timeStr.split("--")
	val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")

	val timeSdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

	val daySdf = SimpleDateFormat("yyyy-MM-dd")
	var startTime = try {
		timeSdf.parse(times[0])
	} catch (e: Exception) {
		daySdf.parse(times[0])
	}
	var endTime = try {
		timeSdf.parse(times[1])
	} catch (e: Exception) {
		daySdf.parse(times[1])
	}
	setTimeTo15Min(startTime)
	setTimeTo15Min(endTime)
	val t = endTime.time - startTime.time
	val toInt = t.div(1000 * 60).toInt()

	println(toInt - (toInt % 15))

}
